package com.xy.iot.service.impl;

import com.xy.iot.serial.port.listener.MySerialPortEventListener;
import com.xy.iot.serial.port.utils.SerialPortUtil;
import com.xy.iot.service.GnuSerialPortService;
import com.xy.iot.config.properties.IotSerialPortProperties;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: niuniu
 * @Date: 2024/6/11 20:41
 * @Description: Gnu组件的串口服务实现类
 */
@Service
@Slf4j
public class GnuSerialPortServiceImpl implements GnuSerialPortService {

    private static SerialPort serialPort;
    @Autowired
    private IotSerialPortProperties iotSerialPortProperties;

    @Override
    public void closeSerialPort() {
        if (serialPort!=null){
            SerialPortUtil.removeListener(serialPort,new MySerialPortEventListener(serialPort));
            SerialPortUtil.closePort(serialPort);
            log.info("串口关闭：{}",iotSerialPortProperties.getPort());
        }else {
            log.error("串口未打开");
        }

    }

    @Override
    public void serialPortSendData(byte[] bytes) {
        if (serialPort!=null){
            SerialPortUtil.sendToPort(serialPort,bytes);
        }else {
            log.error("串口未打开");
        }
    }

    @Override
    public void init() {
        boolean response = false;
        try {
            String portName = iotSerialPortProperties.getPort();
            Integer timeout = iotSerialPortProperties.getTimeout();
            Integer baudRate = iotSerialPortProperties.getBaudRate();
            Integer dataBits = iotSerialPortProperties.getDataBits();
            Integer stopBits = iotSerialPortProperties.getStopBits();
            Integer parity = iotSerialPortProperties.getParity();
            serialPort = SerialPortUtil.openPort(portName, timeout, baudRate,dataBits, stopBits, parity);
            //给对应的serialPort添加监听器
            SerialPortUtil.addListener(serialPort,new MySerialPortEventListener(serialPort));
            log.info("串口初始化：{}", iotSerialPortProperties);
            response = true;
        }catch (Exception e){
            log.error("启动串口发生错误",e);
        }
        if (!response){
            throw new RuntimeException("开启串口失败");
        }
    }
}
